//
//  NSObjectExtension.swift
//  MT
//
//  Created by zhang qiang on 2018/12/2.
//  Copyright © 2019年 张强. All rights reserved.
//

import Foundation
import UIKit

fileprivate struct HudLoadAssociatedKeys {
    static var HudLoadingView: UInt8 = 0
}

extension NSObject {
    internal var loadingView: MTHudLoadingView? {
        set {
            objc_setAssociatedObject(self, &HudLoadAssociatedKeys.HudLoadingView, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
        
        get {
            let obj: MTHudLoadingView? = objc_getAssociatedObject(self, &HudLoadAssociatedKeys.HudLoadingView) as? MTHudLoadingView
            return obj
        }
    }
    
    public func showLoadingView(showView: UIView? = nil) {
        if let view = loadingView, let _ = view.superview {
            view.removeFromSuperview()
        }else{
            loadingView = MTHudLoadingView()
            if showView != nil {
                showView!.addSubview(loadingView!)
            } else {
                if #available(iOS 13.0, *) {
                    UIApplication.mt_keyWindow?.addSubview(loadingView!)
                } else {
                    UIApplication.mt_keyWindow?.addSubview(loadingView!)
                }
            }
            
            loadingView!.snp.makeConstraints({ (make) in
                make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
            })
        }
    }
    
    public func hideLoadingView() -> Void{
        if let view = loadingView {
            view.removeFromSuperview()
        }
    }
}
